using UnityEngine;
using System.Collections.Generic;
using UnityEngine.UI; // 引入UI命名空间
using UnityEngine.EventSystems; // 引入事件系统命名空间

public class Minesweeper : MonoBehaviour
{
    private bool[,] isMine = new bool[10, 10];
    private bool[,] isRevealed = new bool[10, 10];
    private int numRows = 10;
    private int numCols = 10;
    private int numMines = 20;
    private int flagsLeft = 20;
    private int minesRevealed;
    private bool gameStarted;
    private bool gameWon;
    private bool isGameOver = false;
    private int cellSize = 30; // 假设每个格子的大小为30像素


    // 初始化游戏
    void Start()
    {
        InitializeGame();
    }

    // 更新游戏状态
    void Update()
    {
        // 检查是否点击了鼠标左键
        if (Input.GetMouseButtonDown(0) && !isGameOver)
        {
            // 创建一个PointerEventData对象，模拟鼠标点击事件
            PointerEventData eventData = new PointerEventData(EventSystem.current);
            eventData.position = Input.mousePosition;

            // 利用EventSystem进行检测，查看鼠标点击是否在UI元素上
            List<RaycastResult> results = new List<RaycastResult>();
            EventSystem.current.RaycastAll(eventData, results);
            if (results.Count > 0)
            {
                // 鼠标点击在UI元素上，处理点击逻辑
                foreach (RaycastResult result in results)
                {
                    // 将鼠标的屏幕坐标转换为游戏逻辑中的格子坐标
                    Vector2 mousePos = Camera.main.ScreenToWorldPoint(Input.mousePosition);
                    int x = Mathf.FloorToInt(mousePos.x / cellSize);
                    int y = Mathf.FloorToInt(mousePos.y / cellSize);

                    // 确保点击的格子在棋盘范围内
                    if (x >= 0 && x < numCols && y >= 0 && y < numRows)
                    {
                        RevealCell(x, y);
                    }
                }
            }
        }


    }

    // 绘制UI
    void OnGUI()
    {
        GUI.Box(new Rect(10, 10, 300, 300), ""); // 绘制游戏区域的背景框

        for (int x = 0; x < numCols; x++)
        {
            for (int y = 0; y < numRows; y++)
            {
                Rect cellRect = new Rect(10 + x * 30, 10 + y * 30, 30, 30);
                if (isRevealed[x, y])
                {
                    // 绘制已揭示的单元格
                    if (isMine[x, y])
                    {
                        GUI.Label(cellRect, "X");
                    }
                    else
                    {
                        int adjacentMines = CountAdjacentMines(x, y);
                        if (adjacentMines > 0)
                        {
                            GUI.Label(cellRect, adjacentMines.ToString());
                        }
                    }
                }
                else
                {
                    // 绘制未揭示的单元格
                    if (GUI.Button(cellRect, ""))
                    {
                        RevealCell(x, y);
                    }
                }
            }
        }

        // 显示旗帜数量
        GUI.Label(new Rect(10, 320, 300, 20), "Flags left: " + flagsLeft);

        // 游戏结束时显示重置按钮
        if (isGameOver)
        {
            if (gameWon)
            {
                GUI.Label(new Rect(10, 350, 300, 20), "You Win!");
            }
            else
            {
                GUI.Label(new Rect(10, 350, 300, 20), "Game Over!");
            }
            Rect resetRect = new Rect(10, 370, 300, 50);
            if (GUI.Button(resetRect, "Reset Game"))
            {
                InitializeGame();
                isGameOver = false;
                gameWon = false;
            }
        }
    }

    // 初始化游戏，放置地雷
    void InitializeGame()
    {
        isMine = new bool[numRows, numCols];
        isRevealed = new bool[numRows, numCols];
        flagsLeft = numMines;
        minesRevealed = 0;
        gameStarted = true;
        gameWon = false;

        // 随机放置地雷
        for (int i = 0; i < numMines; i++)
        {
            int x, y;
            // 确保位置是有效的，并且没有重复放置地雷
            do
            {
                x = Random.Range(0, numCols);
                y = Random.Range(0, numRows);
            } while (isMine[x, y]);

            isMine[x, y] = true;
        }
    }

    // 揭示一个单元格
    void RevealCell(int x, int y)
    {
        if (isGameOver || isRevealed[x, y] || !IsWithinBoard(x, y))
        {
            return;
        }

        isRevealed[x, y] = true;
        minesRevealed++;

        if (isMine[x, y])
        {
            // 游戏结束
            Debug.Log("Game Over!");
            isGameOver = true;
            ShowAllMines(); // 调用显示所有地雷的方法
            return;
        }

        int adjacentMines = CountAdjacentMines(x, y);
        if (adjacentMines == 0)
        {
            // 自动揭示相邻的单元格
            for (int dx = -1; dx <= 1; dx++)
            {
                for (int dy = -1; dy <= 1; dy++)
                {
                    if (dx != 0 || dy != 0)
                    {
                        int newX = x + dx;
                        int newY = y + dy;
                        if (IsWithinBoard(newX, newY))
                        {
                            RevealCell(newX, newY);
                        }
                    }
                }
            }
        }

        // 检查是否获胜
        if (minesRevealed == numCols * numRows - numMines)
        {
            Debug.Log("You have won the game!");
            isGameOver = true;
            gameWon = true;
        }
    }

    // 计算相邻地雷数量
    int CountAdjacentMines(int x, int y)
    {
        int count = 0;
        for (int dx = -1; dx <= 1; dx++)
        {
            for (int dy = -1; dy <= 1; dy++)
            {
                if (dx != 0 || dy != 0)
                {
                    int newX = x + dx;
                    int newY = y + dy;
                    if (IsWithinBoard(newX, newY) && isMine[newX, newY])
                    {
                        count++;
                    }
                }
            }
        }
        return count;
    }

    void ShowAllMines()
    {
        for (int x = 0; x < numCols; x++)
        {
            for (int y = 0; y < numRows; y++)
            {
                if (isMine[x, y] && !isRevealed[x, y])
                {
                    isRevealed[x, y] = true;
                    // 在OnGUI中将显示这个地雷
                }
            }
        }
    }

    // 检查坐标是否在棋盘内
    bool IsWithinBoard(int x, int y)
    {
        return x >= 0 && x < numCols && y >= 0 && y < numRows;
    }

}